<?php

namespace App\Http\Controllers;

use App\Model\Article;
use App\Model\Cate;
use App\Model\Tag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $articles = Article::orderBy('created_at','desc')->paginate(4);

        return view('article.index', compact('articles'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $tags = Tag::all();
        $cates = Cate::all();
        return view("article.create",compact('cates','tags'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request,Article $article)
    {
        //
        $this -> validate($request,[
            'title'=>'required|min:2|max:30',
            'content'=>'required|min:3',
            'cate_id'=>'required',
        ]);

        $article->title = $request->title;
        $article->content = $request -> content;
        $article->cate_id = $request -> cate_id;
        if (session('articleImg')){
            $article->image = session('articleImg');
        }

        $res = $article->save();
        $request->session()->forget('articleImg');
        if ($res){
            foreach ($request->tag_id as $tag_id){
                $article->tags()->attach($tag_id);
            }

            return [
                'error'=>0,
                'info'=>'添加成功'
            ];
        }

        return [
            'error'=>1,
            'info' => '添加失败'
        ];
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Article $article)
    {
        //
        $article = $article->load('answers','cate');
        # code...
        $articles = Article::orderBy('created_at','desc')->limit(6)->get();
//        dd($articles);
        $cates = Cate::orderBy('created_at','desc')->get();

        $tags = Tag::orderBy('created_at','desc')->limit(4)->get();

        return view('index.article',compact('article','articles','cates','tags'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Article $article)
    {
        //
        $cates = Cate::all();
        $tags = Tag::all();
        return view('article.edit',compact('article','cates','tags'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Article $article)
    {
        //
        $this -> validate($request,[
            'title'=>'required|min:2|max:30',
            'content'=>'required|min:3',
            'cate_id'=>'required',
        ]);
        $article->title = $request->title;
        $article->content = $request -> content;
        $article->cate_id = $request -> cate_id;
//        dd(session('articleImg'));
        if (session('articleImg')){
            $article->image = session('articleImg');
            $request->session()->forget('articleImg');
        }
        $res = $article ->save();

        if ($res){
            return [
                'error'=>0,
                'info'=>'修改成功'
            ];
        }

        return [
            'error'=>1,
            'info' => '修改失败'
        ];


    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function upload(Request $request)
    {
        if ($request->isMethod('post')) {

            $file = $request->file('file');
            // 文件是否上传成功
            if ($file->isValid()) {
                // 获取文件相关信息
                $ext = $file->getClientOriginalExtension();     // 扩展名
                $realPath = $file->getRealPath();   //临时文件的绝对路径
                // 上传文件
                $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
                // 使用我们新建的uploads本地存储空间（目录）
                $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
                if ($bool){
                    return[
                        "code"=>0 //0表示成功，其它失败
                        ,"data"=>[
                            "src"=>"/uploads/".$filename
                        ]

                    ];
                }
            }
        }
    }


    public function articleStatus(Article $article)
    {
        if($article->status == '0'){
            $article->status ='1';
        }else{
            $article->status = '0';
        }

        $article->save();
    }

    public function articleImg(Request $request)
    {
        if ($request->isMethod('post')) {

            $file = $request->file('file');
            // 文件是否上传成功
            if ($file->isValid()) {
                // 获取文件相关信息
                $ext = $file->getClientOriginalExtension();     // 扩展名
                $realPath = $file->getRealPath();   //临时文件的绝对路径
                // 上传文件
                $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
                // 使用我们新建的uploads本地存储空间（目录）
                $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
                if ($bool){
                    session(['articleImg'=>'/uploads/'.$filename]);
                }
            }
        }
    }

}
